<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/26
 * Time: 10:13
 */

namespace Admin\Controller;

use Admin\Model\AdminUserModel;
use Common\Util\CommonUtil;
use Common\Util\PageWrap;

class AdminUserController extends AdminSessionBaseController
{
    // 查询
    public function query() {
        $data = I('get.');
        $page = I('get.page');
        $limit = I('get.limit');
        if(isset($data['keyword'])){
            $where['account']=array('like','%'.$data['keyword'].'%');
        }
        $loginMdl = new AdminUserModel();

        $ret = $loginMdl
            ->where($where)
            ->page($page,$limit)
            ->order('create_time desc')
            ->select();

        $total = $loginMdl->where($where)->count();

        $page_data = PageWrap::wrap($ret,$total,$page,$limit);

        $this->ajaxReturnWrap($page_data,0,'操作成功');
    }

    // 添加 / 修改
    public function save() {
        $data = I('post.');

        $loginMdl = new AdminUserModel();

        if(!$loginMdl->create($data)) {
            $this->ajaxReturnWrap(null,1,$loginMdl->getError());
        } else {
            if(!isset($data['id'])) {
                $loginMdl->type = 1;
                $loginMdl->create_time=CommonUtil::getTimeString();
                $ret = $loginMdl->add();
            } else {
                $ret = $loginMdl->save();
            }

            if($ret < 0) {
                $this->ajaxReturnWrap(null,2,'操作失败');
            }
            $this->ajaxReturnWrap(null,0,'操作成功');
        }
    }

    // 删除
    public function delete($id) {
        $loginMdl = new AdminUserModel();
        $ret = $loginMdl->delete($id);
        if($ret < 0) {
            $this->ajaxReturnWrap(null,1,'操作失败');
        }
        $this->ajaxReturnWrap($ret,0,'操作成功');
    }

    // 修改密码
    public function changePwd() {

        $old_pwd=I('get.old_pwd');
        $new_pwd=I('get.new_pwd');
        $new_pwd_confirm=I('get.new_pwd_confirm');

        $loginMdl = new AdminUserModel();

        if(!$old_pwd) {
            $this->ajaxReturnWrap(null,1,'当前密码不能为空');
        }
        if(!$new_pwd) {
            $this->ajaxReturnWrap(null,1,'新密码不能为空');
        }

        if($new_pwd != $new_pwd_confirm) {
            $this->ajaxReturnWrap(null,1,'两次输入的新密码不匹配');
        }

        if($new_pwd == $old_pwd) {
            $this->ajaxReturnWrap(null,1,'新密码不能和当前密码一样');
        }

        $user_id = $this->user_id;

        $ret = $loginMdl->where(['id'=>$user_id,'password'=>$old_pwd])->find();

        if(!$ret) {
            $this->ajaxReturnWrap(null,2,'原始密码不正确');
        }

        $ret = $loginMdl->where(['id'=>$user_id])->save(['password'=>$new_pwd]);

        if($ret) {
            $this->ajaxReturnWrap(null,0,'操作成功');
        } else {
            $this->ajaxReturnWrap(null,1,'操作失败');
        }

    }
}